// import io from '@hyoga/uni-socket.io';
// import io from 'socket.io-client'
import io from '@/store/weapp.socket.io.js';
import store from '@/store/index.js'
export default class Chat {
  constructor() {
    this.instance = null;
    this.token = null;
    this.socket = io('http://172.15.254.12:7001/');
  }

  getInstance() {
    if (!this.instance) {
      this.instance = new Chat();
    }
    return this.instance;
  }
  setup() {
    console.log('已连接');
    this.token = uni.getStorageSync('Access-Token');
    if (!this.token) return;
    // const socket = io("ws://172.15.254.12:7001/", {
    //   transports: ["websocket", "polling"] // use WebSocket first, if available
    // });
    // const socket = io('http://172.15.254.12:7001/');
    // this.socket = socket;
    this.socket.on('connect', () => {
      // console.log('ws已连接');
      const user = JSON.parse(uni.getStorageSync('userInfo'))
      if (user) {
        this.socket.emit('join', {
          userId: user.id
        });
      }
      // const {
      //   id
      // } = socket;
      this.socket.on('res', (data) => {
        console.log('ws 收到服务器消息：', data);
        store.commit('retransmission', data)
      });
      this.socket.on('msg', data => {
        console.log('收到群聊消息：', data);
      })
    });
    this.socket.on('error', (msg) => {
      // console.log('ws error', error);
    });
  }
  /**
   * 接收到好友发来消息
   * @param data { CHAT_MESSAGE } 接收到的好友消息
   */
  onMessage(data) {
    const {
      messages,
      sender_id
    } = data;
    store.dispatch('message/setMessage', {
      messages
    });
    store.dispatch('user/setRecentContact', {
      friend_id: sender_id
    });
  }
  sendMessage(data) {
    console.log(data, '====', this.socket);
    if (!this.socket) return;
    this.socket.emit('message', data)
    // const {
    //   user_info,
    //   friend_info,
    //   is_group
    // } = options;

    // const message = {
    //   hash: md5(`${user_info.id}_${friend_info.friend_id}_${+new Date()}`),
    //   user_id: user_info.id,
    //   dist_id: friend_info.friend_id,
    //   dist_type: is_group ? ENUM_MESSAGE_DIST_TYPE.GROUP : ENUM_MESSAGE_DIST_TYPE.PRIVATE,
    //   content_type: ENUM_MESSAGE_CONTENT_TYPE.TEXT,
    //   content,
    //   create_time: +new Date(),
    // };
    // const record = {
    //   ...message,
    //   is_owner: 1,
    // };
    // this.socket.emit('message', {
    //   message
    // });
    // store.dispatch('message/setMessage', {
    //   messages: [record]
    // });
    // store.dispatch('user/setRecentContact', {
    //   friend_id: friend_info.friend_id
    // });
  }
}
// export default Chat.getInstance();
